// pages/login/index.js
const app = getApp();
var topOpacity = 0;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    // 组件参数设置，传递到组件
    defaultData: {
      title: "登录注册", // 导航栏标题
      showHome: false, //是否显示回到首页按钮
      showBack: true, //是否显示返回按钮
      showLogo: false, //是否显示logo
      bgColor: 'transparent',
      goUrl: ''
    },
    baseUrl: app.baseUrl,
    version: app.globalData.version,
    navBarHeight: app.globalData.navBarHeight,
    // 姓名
    name: '',
    // 电话
    phone: '',
    //验证码
    code: '',
    codeDjs: 0,

    openid: '',
    shareTitle: '',
    shareImg: '',
    is_register: 0,
    sendTel: '',
    sendSjc: 0,
    sendCode: '',
    registerInfo: [],
    showStatement: false, //是否弹出协议框
    showAgreement: false, //单个隐私协议内容
    choose1: false,
    choose2: false,
    choose3: false,
    agreement_title: "用户协议",
    html: '',
    flag: 0,
    rebindToken: '', //换绑凭证
    isBj: 0 //是否是本机登录跳转的页面
  },
  onPageScroll(t) {
    if (t.scrollTop < 40) {
      topOpacity = 0
      if (this.data.topOpacity != 0) {
        this.setData({
          topOpacity: 0
        })
      }
    } else if (t.scrollTop >= 40) {
      if (topOpacity <= 1) {
        topOpacity = t.scrollTop / 100 - .4
      } else {
        topOpacity = 1
      }
      if (topOpacity <= 1) {
        this.setData({
          topOpacity: topOpacity
        })
      }
    }
  },

  //14岁协议
  choose1() {
    this.setData({
      // 点击之后进行取反
      choose1: !this.data.choose1
    })
  },
  //用户协议
  choose2() {
    this.setData({
      // 点击之后进行取反
      choose2: !this.data.choose2
    })
  },
  //隐私协议
  choose3() {
    this.setData({
      // 点击之后进行取反
      choose3: !this.data.choose3
    })
  },

  //不同意协议
  disagree() {
    this.setData({
      showStatement: false
    })
  },
  //同意协议
  agree() {

    var choose1 = this.data.choose1;
    var choose2 = this.data.choose2;
    var choose3 = this.data.choose3;

    //var radioValue = this.data.radioValue;
    if (!choose1) {
      app.showTip("请确认年龄信息与实际年龄相符");
      return;
    }
    if (!choose2) {
      app.showTip("请勾选并同意《麓悦江城线上中心小程序用户服务协议》");
      return;
    }
    if (!choose3) {
      app.showTip("请勾选并同意《麓悦江城线上中心小程序隐私权政策》");
      return;
    }


    this.setData({
      showStatement: false,
    });
    wx.setStorageSync('firstXy', 1);
  },

  //关闭隐私详情
  closeAgreement() {
    this.setData({
      showAgreement: false,
      html: '',
      agreement_title: ''
    })
  },

  //查询协议内容
  getXyContent(e) {
    var that = this;
    var id = e.currentTarget.dataset.id;
    wx.showLoading({
      title: '数据加载中...'
    });
    wx.request({
      url: that.data.baseUrl + 'getXyContent.php',
      method: 'POST',
      data: {
        'id': id
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //后台请求成功
          that.setData({
            html: that.formatRichText(res.data.info['content']),
            agreement_title: res.data.info.title,
            showAgreement: true,
          })
        } else {
          //后台请求失败
          app.showTip(res.data.msg);

        }
      },
      fail: function (res) {
        wx.hideLoading();
      }
    });
  },

  // 姓名
  nameIpt(e) {
    this.setData({
      name: e.detail.value
    })
  },
  // 电话
  phoneIpt(e) {
    this.setData({
      phone: e.detail.value
    })
  },
  // 验证码
  codeIpt(e) {
    this.setData({
      code: e.detail.value
    })
  },
  //发送验证码
  sendCode() {
    let that = this;

    //判断是否同意了隐私协议
    if (wx.getStorageSync('firstXy') == undefined || wx.getStorageSync('firstXy') == '') {
      if (that.data.choose1 == false || that.data.choose2 == false || that.data.choose3 == false) {
        that.setData({
          showStatement: true
        });
        return;
      }
    }

    //判断是否重复点击
    if (that.data.codeDjs > 0 && that.data.codeDjs < 60) {
      return;
    }
    if (that.data.phone.trim() === '') {
      app.showTip("请输入电话")
    } else if (that.data.phone.trim().length != 11) {
      app.showTip("请输入正确的电话")
    } else {


      //后台请求发送验证码
      wx.showLoading({
        title: '验证码发送中...'
      });
      wx.request({
        url: that.data.baseUrl + 'sms/sendCode.php',
        method: 'POST',
        data: {
          openid: that.data.openid,
          tel: that.data.phone.trim()
        },
        header: {
          'content-type': 'application/x-www-form-urlencoded'
        },
        success: function (res) {
          wx.hideLoading();
          app.showTip(res.data.msg);
          if (res.data.status == 1) {
            that.setData({
              sendTel: res.data.sendTel,
              sendSjc: res.data.sendSjc,
              sendCode: res.data.sendCode
            });
            //处理时间
            that.setData({
              codeDjs: 60
            })
            let interval = setInterval(function () {
              if (that.data.codeDjs > 0) {
                that.data.codeDjs--;
                console.log(that.data.codeDjs)
                that.setData({
                  codeDjs: that.data.codeDjs
                })
              } else {
                clearInterval(interval);
              }
            }, 1000);
          }
        },
        fail: function (res) {
          wx.hideLoading();
          app.showTip('服务器繁忙,请稍候重试');
        }
      });
    }
  },

  //登录注册控制
  loginHandle() {
    var that = this;
    that.login(0);
  },

  //登录注册
  login(isHb) {
    let that = this;

    //判断是否同意了隐私协议
    if (wx.getStorageSync('firstXy') == undefined || wx.getStorageSync('firstXy') == '') {
      if (that.data.choose1 == false || that.data.choose2 == false || that.data.choose3 == false) {
        that.setData({
          showStatement: true
        });
        return;
      }
    }

    if (that.data.name.trim() === '') {
      app.showTip("请输入姓名");
      return;
    } else if (that.data.phone.trim() === '') {
      app.showTip("请输入电话");
      return;
    } else if (that.data.code.trim() === '' && that.data.isBj == 0) {
      app.showTip("请输入验证码");
      return;
    } else if ((that.data.code.trim().length != 6 || isNaN(that.data.code.trim())) && that.data.isBj == 0) {
      app.showTip("请输入6位数字的验证码");
      return;
    } else if (that.data.sendTel != that.data.phone.trim() && that.data.sendTel != '' && that.data.isBj == 0) {
      app.showTip("抱歉,您提交的电话号码和发送短信的电话号码不一致");
      return;
    } else if (that.data.sendCode != that.data.code.trim() && that.data.sendCode != '' && that.data.isBj == 0) {
      app.showTip("验证码错误");
      return;
    }

    if (that.data.flag == 0) {
      that.setData({
        flag: 1
      });
      //后台请求发送验证码
      wx.login({
        success: function (res) {
          if (res.code) {
            wx.showLoading({
              title: '信息提交中...',
              mask: true
            });
            var timestamp = new Date().getTime();
            wx.setStorageSync('sendTimestamp', timestamp);
            wx.request({
              url: that.data.baseUrl + 'addRegister.php',
              method: 'POST',
              data: {
                openid: that.data.openid,
                tel: that.data.phone.trim(),
                name: that.data.name.trim(),
                code: that.data.code.trim(),
                sendCode: that.data.sendCode,
                sendTel: that.data.sendTel,
                sendSjc: that.data.sendSjc,
                wxCode: res.code,
                isHb: isHb,
                rebindToken: that.data.rebindToken,
                isBj: that.data.isBj
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                wx.hideLoading();
                app.showTip(res.data.msg);
                if (res.data.status == 1) {
                  //判断是否有回跳的url
                  var loginHeaderUrl = wx.getStorageSync('loginHeaderUrl');
                  var loginHeaderType = wx.getStorageSync('loginHeaderType');
                  if (loginHeaderUrl != '' && loginHeaderUrl != undefined) {
                    //回跳其他页
                    //清空缓存
                    wx.setStorageSync('loginHeaderUrl', '');
                    wx.setStorageSync('loginHeaderType', '');
                    if (loginHeaderType == 'switchTab') {
                      wx.switchTab({
                        url: loginHeaderUrl
                      });
                    } else if (loginHeaderType == 'redirectTo') {
                      wx.redirectTo({
                        url: loginHeaderUrl
                      });
                    } else {
                      wx.navigateTo({
                        url: loginHeaderUrl
                      });
                    }
                  } else {
                    //回跳首页
                    wx.switchTab({
                      url: '/pages/index/index'
                    });
                  }
                } else if (res.data.status == 100) {
                  that.setData({
                    rebindToken: res.data.rebindToken
                  });
                  //提示是否换绑
                  wx.showModal({
                    title: '温馨提示',
                    content: '当前微信号已与其他账号绑定,是否确认将此微信号换绑到即将登录的账号下?',
                    complete: (res) => {
                      if (res.confirm) {
                        that.login(1);
                      }
                    }
                  });
                  that.setData({
                    flag: 0
                  });
                } else {
                  that.setData({
                    flag: 0
                  });
                }
              },
              fail: function (res) {
                wx.hideLoading();
                app.showTip('服务器繁忙,请稍候重试');
                that.setData({
                  flag: 0
                });
              }
            });
          }
        }
      });
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    var that = this;
    var isBj = options.isBj;
    var tel = options.tel;
    if (isBj == 1 && tel.length == 11) {
      that.setData({
        isBj: isBj,
        phone: tel
      });
    }

    //判断是否同意过协议
    if (wx.getStorageSync('firstXy') == '' || wx.getStorageSync('firstXy') == undefined) {
      that.setData({
        showStatement: true
      });
    }

    var loginHeaderUrl = wx.getStorageSync('loginHeaderUrl');
    that.setData({
      ['defaultData.goUrl']: loginHeaderUrl
    });

    //获取缓存中的openid
    var openid = wx.getStorageSync('ly24_openid');

    if (openid == '') {
      //缓存中没有openid
      //获取所需页面信息
      wx.login({
        success: function (res) {
          if (res.code) {
            //发起网络请求
            wx.request({
              url: that.data.baseUrl + 'getOpenid.php',
              method: 'POST',
              data: {
                'code': res.code
              },
              header: {
                'content-type': 'application/x-www-form-urlencoded'
              },
              success: function (res) {
                //缓存微信openid
                wx.setStorageSync('ly24_openid', res.data.openid);
                that.setData({
                  openid: res.data.openid
                });

                //获取本页数据
                that.getLoginPageInfo(res.data.openid);
              },
              fail: function (res) {}
            });
          }
        }
      });
    } else {
      that.setData({
        openid: openid
      });

      //获取本页数据
      that.getLoginPageInfo(openid);
    }

    //调用分享
    that.getShareInfo();
  },

  //获取本业数据
  getLoginPageInfo(openid) {
    var that = this;
    wx.showLoading({
      title: '数据加载中...'
    })
    wx.request({
      url: that.data.baseUrl + 'getLoginPageInfo.php',
      method: 'POST',
      data: {
        'openid': openid
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.hideLoading();
        if (res.data.status == 1) {
          //重新赋值后台请求数据
          /*if (res.data.is_register == 1) {
            //已经注册过了
            app.showTip('您已经注册过了哦');
            setTimeout(function () {
              wx.switchTab({
                url: '/pages/index/index'
              })
            }, 1500);
          }*/

          if (res.data.registerInfo.tel.length > 0 && that.data.isBj == 0) {
            that.setData({
              registerInfo: res.data.registerInfo,
              phone: res.data.registerInfo.tel,
              name: res.data.registerInfo.name
            });
          } else if (that.data.isBj == 1) {
            that.setData({
              registerInfo: res.data.registerInfo,
              name: res.data.registerInfo.name
            });
          }
        } else {
          app.showTip(res.data.msg);
          setTimeout(function () {
            wx.navigateBack({
              delta: 1
            });
          }, 2000);
        }
      },
      fail: function () {
        wx.hideLoading();
        app.showTip('抱歉,服务器繁忙');
        setTimeout(function () {
          wx.navigateBack({
            delta: 1
          });
        }, 2000);
      }
    });
  },


  //获取微信分享信息
  getShareInfo() {
    var that = this;
    wx.request({
      url: that.data.baseUrl + 'getShareInfo.php',
      method: 'POST',
      data: {

      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        that.setData({
          shareTitle: res.data.shareTitle,
          shareImg: res.data.shareImg
        });
      },
      fail: function (res) {}
    });
  },

  /**
   * 处理富文本里的图片宽度自适应
   * 1.去掉img标签里的style、width、height属性
   * 2.img标签添加style属性：max-width:100%;height:auto
   * 3.修改所有style里的width属性为max-width:100%
   * 4.去掉<br/>标签
   * @param html
   * @returns {void|string|*}
   */
  formatRichText(html) {
    let newContent = html.replace(/<img[^>]*>/gi, function (match, capture) {
      match = match.replace(/style="[^"]+"/gi, '').replace(/style='[^']+'/gi, '');
      match = match.replace(/width="[^"]+"/gi, '').replace(/width='[^']+'/gi, '');
      match = match.replace(/height="[^"]+"/gi, '').replace(/height='[^']+'/gi, '');
      return match;
    });
    newContent = newContent.replace(/style="[^"]+"/gi, function (match, capture) {
      match = match.replace(/width:[^;]+;/gi, 'width:100%;').replace(/width:[^;]+;/gi, 'width:100%;');
      return match;
    });
    newContent = newContent.replace(/<br[^>]*\/>/gi, '');
    newContent = newContent.replace(/\<img/gi, '<img style="width:100%;height:auto;display:block;margin:10px 0;"');
    return newContent;
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    var that = this;
    return {
      title: that.data.shareTitle,
      path: '/pages/index/index',
      imageUrl: that.data.shareImg,
      success: function (res) {

      },
      fail: function (res) {

      }
    }
  }
})